﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Web.Hosting;

namespace StripeOne.Core.Log
{
    public class StripeOneLog
    {
        #region Attributes

        public static string FileName { get; set; }

        #endregion

        #region Private Methods

        private static string GetConfig(string key)
        {
            XDocument xml = XDocument.Load(HostingEnvironment.ApplicationPhysicalPath + "\\Config\\StripeOne.xml");
            XElement xmlElements = null;

            if (xml != null)
            {
                xmlElements = (from item in xml.Root.Descendants("default")
                               select item.Element(key)).FirstOrDefault();

            }
            return xmlElements != null ? xmlElements.Value : "[default" + "/" + key + "]";
        }

        private static void Write(string message)
        {
            var path = GetConfig("logPath");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            path += "StripeOne_" + FileName;
            var logMessage = DateTime.Now + ": " + message;

            using (var fileStream = new FileStream(path, FileMode.OpenOrCreate))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    writer.BaseStream.Seek(0, SeekOrigin.End);
                    writer.WriteLine(logMessage);
                }
            }
        }

        #endregion

        #region Public Methods

        public StripeOneLog() { }

        public static void Verbose(string message)
        {
            FileName = DateTime.Today.ToString("yyyyMMdd") + "_Verbose.txt";
            StripeOneLog.Write(message);
        }

        public static void Exception(Exception exception)
        {
            FileName = DateTime.Today.ToString("yyyyMMdd") + "_Exception.txt";
            StripeOneLog.Write("[" + exception.Message + "] - " + exception.StackTrace);
        }

        public static void Warning(string message)
        {
            FileName = DateTime.Today.ToString("yyyyMMdd") + "_Warning.txt";
            StripeOneLog.Write(message);
        }

        #endregion
    }
}
